﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LDSP.Util;
using LDSP.Helper;

namespace LDSP.UI
{
    public partial class AdminLogin : BRL.BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string userName = LDSPCookie.GetInstance().GetCookie(Request, CookieKeys.AdminUserName);
                string password = LDSPCookie.GetInstance().GetCookie(Request, CookieKeys.AdminPassword);

                bool fobidAutoLogin = Request.QueryString["FOBID_AUTO_LOGIN"] == "true";
                if (!fobidAutoLogin && !string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
                {
                    this.Session.Add(SessionKeys.AutoLogin, "AUTO_U_LOGIN");
                    LoginWithCookie(userName, password, string.Empty, false);
                }
            }
        }

        public override void RedirectBefore()
        {
            //Note：本页面不需要进行页面跳转判断
        }

        protected void btn_ok_Click(object sender, EventArgs e)
        {
            try
            {
                LoginWithCookie(this.txt_name.Text.Trim(), this.txt_pwd.Text, this.txt_validate.Text, this.chkRememberMe.Checked);

                {
                    string redirectUrl = string.Empty;

                    if (LoginAdmin != null)
                    {
                        redirectUrl = "~/UI/Admin/Index.aspx";
                        this.Response.Redirect(redirectUrl);
                    }
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        private void LoginWithCookie(string userName, string password, string validateCode, bool needWriteCookie)
        {
            if (this.Login(userName, password, validateCode, 0))
            {
                this.Session.Remove(SessionKeys.AutoLogin);

                //写cookie.
                if (needWriteCookie)
                {
                    new LDSPCookie().WriteCookie(Response, CookieKeys.AdminUserName, this.txt_name.Text.Trim());
                    new LDSPCookie().WriteCookie(Response, CookieKeys.AdminPassword, this.txt_pwd.Text);
                }

                //页面跳转.
                string redirectUrl = string.Empty;
                if (LoginAdmin != null)
                {
                    redirectUrl = "~/UI/Admin/Index.aspx";
                    this.Response.Redirect(redirectUrl);
                }
            }
        }
    }
}